package cn.i96688.scanclient.utils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import cn.i96688.scanclient.bean.PayLog;

public class AppEnv {
	public final static int port=52345;
	private static Server server=null;

	static class Server extends Thread{
		final static String MSG="sc.server"; 
		ServerSocket serverSocket=null;
		private boolean start=true;
		Server(int port){
			try {
				serverSocket =new ServerSocket(port);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		void stopService(){
			try {
				start=false;
				serverSocket.close();
			} catch (IOException e) {
				PayLog.getInstance().addLogs(e);
			}
		}
		void service(){
			Socket socket =null;
			DataInputStream reader = null;
			DataOutputStream writer=null;
			try {
				//2、调用accept()方法开始监听，等待客户端的连接
				socket = serverSocket.accept();
				//3、获取输入流，并读取客户端信息
				reader = new DataInputStream(socket.getInputStream());  
				String msg=reader.readUTF();
			    System.out.println("request_client_msg="+msg);  
				if(Client.MSG.equals(msg)){
					//4、获取输出流，响应客户端的请求
					writer=new DataOutputStream(socket.getOutputStream());
					writer.writeUTF(Server.MSG);
					writer.flush();
				}
			} catch (IOException e) {
				PayLog.getInstance().addLogs(e);
			}finally{
				try {
					if(reader!=null)
						reader.close();
				} catch (Exception e2) {
				}
				try {
					if(writer!=null)
						writer.close();
				} catch (Exception e2) {
				}
				try {
					if(socket!=null)
						socket.close();
				} catch (Exception e2) {
				}
			}
		}
		@Override
		public void run() {
			while(start){
				service();
			}
		}
	}
	static class Client{
		final static String MSG="sc.client"; 
		int request(int port){
			try {
				//1、创建客户端Socket，指定服务器地址和端口
				Socket socket =new Socket("127.0.0.1",port);
				socket.setSoTimeout(100);
				 
                //向服务器端发送数据    
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());    
                out.writeUTF(Client.MSG);
                
              //读取服务器端数据    
                DataInputStream input = new DataInputStream(socket.getInputStream());    
                String msg = input.readUTF();     
                
                out.close();
                input.close();
				socket.close();
				System.out.println("request_server_msg="+msg);
				if(Server.MSG.equals(msg)){
					PayLog.getInstance().addLog("该程序已经启动了一个实例");
					return 1;//程序启动并存活
				}else{
					PayLog.getInstance().addLog("端口号"+port+"被其它程序占用");
					return 3;// 端口被其它应用占用
				}
			} catch (Exception e) {
				PayLog.getInstance().addLog("服务没有启动，可以启动一个实例");
				String msg=e.getLocalizedMessage();
				if(msg.indexOf("Connection refused")==-1)
					PayLog.getInstance().addLogs(e);
				return 2;//程序没启动
			}
		}
	}
	
	public static void startServer(){
		server=new Server(port);
		server.start();
	}
	public static void stopServer(){
		if(server!=null){
			server.stopService();
		}
	}
	/**
	 * 本程序是否已经启动并存在一个 
	 * 存在，返回true 
	 * 不存在，返false，并写入当前pid到文件里
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static boolean appOnExist() throws Exception {
		Client client=new Client();
		int msg=client.request(port);
		if(msg==1){
			
			return true;
		}else if(msg==2)
			return false;
		else
			throw new Exception("端口"+port+"被其它程序占用");
	}
	public static void test(){
		System.out.println(new Client().request(port));
	}
	public static void main(String[] args) {
		new Server(port).start();
		
	}
}
